import { Card, Button, Steps, Input, Form, Select, message } from 'antd';
import { motion } from 'framer-motion';
import { Download, FolderOpen, Settings, CheckCircle } from 'lucide-react';
import { open } from '@tauri-apps/api/dialog';
import { invoke } from '@tauri-apps/api/tauri';
import { listen } from '@tauri-apps/api/event';
import { useState, useEffect } from 'react';
import LogViewer from '../components/LogViewer';

const { Step } = Steps;
const { Option } = Select;

const SteamSetup = () => {
  const [installPath, setInstallPath] = useState('');
  const [currentStep, setCurrentStep] = useState(0);
  const [logs, setLogs] = useState<string[]>([]);
  const [isInstalling, setIsInstalling] = useState(false);

  // 监听来自 Rust 后端的日志事件
  useEffect(() => {
    const unlistenLog = listen('steamcmd-log', (event) => {
      const logMessage = event.payload as string;
      setLogs(prev => [...prev, logMessage]);
      
      // 检查是否是错误信息
      if (logMessage.includes('失败') || logMessage.includes('错误') || logMessage.includes('Error')) {
        setIsInstalling(false); // 停止 loading 状态
      }
    });
    // 监听 SCUM 安装完成事件
    const unlistenScum = listen('scum-install-finished', () => {
      setIsInstalling(false); // 停止 loading 状态
      setCurrentStep(2); // 直接跳到完成页
    });
    // 监听安装完成标记事件
    const unlistenMark = listen('mark-installation-complete', (event) => {
      const installPath = event.payload as string;
      setInstallPath(installPath);
    });
    return () => {
      unlistenLog.then(f => f());
      unlistenScum.then(f => f());
      unlistenMark.then(f => f());
    };
  }, []);

  // 检查安装状态
  useEffect(() => {
    const checkInstallStatus = async () => {
      try {
        const config = await invoke('get_config') as any;
        if (config.scum_server_installed) {
          setInstallPath(config.install_path);
          setCurrentStep(2); // 直接跳转到完成页面
        }
      } catch (error) {
        console.error('检查安装状态失败:', error);
      }
    };
    
    checkInstallStatus();
  }, []);

  // 检查路径是否包含中文字符
  const hasChineseCharacters = (path: string) => {
    return /[\u4e00-\u9fff]/.test(path);
  };

  const handleBrowseFolder = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择 SteamCMD 安装目录'
      });
      
      if (selected && typeof selected === 'string') {
        // 检查是否包含中文字符
        if (hasChineseCharacters(selected)) {
          message.error('安装路径不能包含中文字符，请选择不包含中文的目录！');
          setInstallPath('');
          return;
        }
        
        setInstallPath(selected);
      }
    } catch (error) {
      console.error('选择目录失败:', error);
    }
  };

  // 处理输入框手动输入
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    
    // 检查是否包含中文字符
    if (hasChineseCharacters(value)) {
      message.error('安装路径不能包含中文字符！');
      setInstallPath('');
      return;
    }
    
    setInstallPath(value);
  };

  // 真正的 SteamCMD 下载功能
  const downloadSteamCMD = async () => {
    try {
      setIsInstalling(true);
      setLogs([]);
      
      console.log('开始调用后端 download_steamcmd 命令，安装路径:', installPath);
      
      // 调用后端的 download_steamcmd 命令
      const result = await invoke('download_steamcmd', { installPath });
      
      console.log('后端命令执行完成，结果:', result);
      
      // 注意：这里不设置 setIsInstalling(false)，因为下载过程是异步的
      // 真正的完成状态由事件监听器处理
      
    } catch (error) {
      console.error('下载失败:', error);
      message.error(`下载失败: ${error}`);
      setLogs(prev => [...prev, `错误: ${error}`]);
      setIsInstalling(false); // 只有出错时才停止 loading
    }
  };

  // 处理下一步按钮
  const handleNext = async () => {
    if (currentStep === 0) {
      if (!installPath.trim()) {
        message.error('请选择安装目录！');
        return;
      }
      setCurrentStep(1);
      await downloadSteamCMD();
    }
  };

  // 处理上一步按钮
  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  // 渲染不同步骤的内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Card className="card" style={{ background: '#262626' }}>
            <Form layout="vertical" className="space-y-6">
              <Form.Item 
                label="安装目录" 
                name="installPath"
                rules={[{ required: true, message: '请选择安装目录' }]}
              >
                <Input.Group compact>
                  <Input 
                    placeholder="C:\\SteamCMD" 
                    value={installPath}
                    onChange={handleInputChange}
                    style={{ width: 'calc(100% - 70px)' }}
                    className="bg-dark-secondary border-dark-border text-text-primary"
                  />
                  <Button 
                    className="btn-secondary" 
                    onClick={handleBrowseFolder}
                    style={{ 
                      width: '60px',
                      height: '40px',
                      marginLeft: '8px'
                    }}
                  >
                    浏览
                  </Button>
                </Input.Group>
              </Form.Item>
            </Form>
          </Card>
        );
      case 1:
        return (
          <LogViewer 
            logs={logs}
            title="SteamCMD 下载日志"
            height={400}
          />
        );
      case 2:
        return (
          <Card className="card" style={{ background: '#262626' }}>
            <div className="text-center space-y-4">
              <CheckCircle size={48} className="text-accent-500 mx-auto" />
              <h3 className="text-xl font-semibold">安装完成</h3>
              <p className="text-text-secondary">SteamCMD 及 SCUM 服务器已成功安装到指定目录</p>
              <div className="bg-dark-secondary p-4 rounded-lg text-left">
                <p><strong>安装路径:</strong> {installPath}</p>
                <p><strong>安装状态:</strong> <span className="text-accent-500">已完成</span></p>
              </div>
            </div>
          </Card>
        );
      default:
        return null;
    }
  };

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }} 
      animate={{ opacity: 1, y: 0 }} 
      transition={{ duration: 0.6 }}
      className="space-y-6"
    >
      <div className="card-container">
        <Card className="card ">
          <div className="text-center space-y-4 mb-8">
            <h1 className="text-gradient text-3xl font-bold">Ac.God.Panel - SteamCMD 安装向导</h1>
            <p className="text-text-secondary text-lg">选择安装位置并自动下载配置 SteamCMD，不要关闭窗口会导致安装失败</p>
          </div>

          <Steps current={currentStep} className="mb-8">
            <Step title="选择安装位置" icon={<FolderOpen size={20} />} />
            <Step title="下载 SteamCMD" icon={<Download size={20} />} />
            <Step title="完成安装" icon={<CheckCircle size={20} />} />
          </Steps>

          <div className="card-container">
            {renderStepContent()}
          </div>

          <div className="flex justify-center space-x-4 mt-6">
            {currentStep > 0 && currentStep < 2 && !isInstalling && (
              <Button size="large" className="btn-secondary" onClick={handlePrev}>
                上一步
              </Button>
            )}
            {currentStep === 0 && (
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                onClick={handleNext}
                disabled={!installPath.trim()}
              >
                下一步
              </Button>
            )}
            {currentStep === 1 && (
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                loading={isInstalling}
                disabled={isInstalling}
              >
                {isInstalling ? '安装中...' : '等待安装完成'}
              </Button>
            )}
       
          </div>
        </Card>
      </div>
    </motion.div>
  );
};

export default SteamSetup; 